import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {InterbankService} from "../interbank.service";
import {Subscription} from "rxjs/Subscription";
import {Router} from "@angular/router";
import * as _ from "lodash";
import {Util} from "../../../common/util";
import {PaginationModel} from "../../../widgets/pagination/pagination.component";
import {Observable} from "rxjs/Observable";

/**
 * 基金划款指令---托管行数据模型
 */
export interface FundConfigBankModel {
  bankId: string;
  toSendTradeOrder: string;
  paymentMethod: string;
  shortName?: string;
  fullName?: string;
  note?: string;
}

/**
 * 基金划款指令---基金配置数据模型
 */
export interface FundConfigModel {
  bankId: string;
  fundCode: string;
  fundName: string;
  toSendTradeOrder: string;
  paymentMethod: string;

  [propName: string]: any;
}

/**
 * 基金划款指令---基金配置模态框数据模型
 *
 */
interface FundConfigModalDataModel {
  fundCode: string;
  fundName: string;
  toSendTradeOrder: string;
  paymentMethod: string;
  note: string;
}

/**
 * 支付参数配置组件
 */
@Component({
  selector: 'interbank-fund-config',
  templateUrl: './fund-config.component.html',
  styleUrls: ['./fund-config.component.scss']
})
export class FundConfigComponent implements OnInit {

  /**
   * 将lodash函数缓存到对象中，以便在组件对象内部和模版中使用
   * @type {_.LoDashStatic|_}
   * @private
   */
  public _ = _;

  /**
   * 支付参数配置---基金列表视图显示状态数据模型
   * @type {{global: boolean; detail: boolean}}
   */
  public configViewStatus = {
    global: false,
    detail: true
  };

  /**
   * 托管行列表数据
   * @type {Array}
   */
  public bankListData: Array<FundConfigBankModel> = [];

  /**
   * 根据用户搜索条件过滤后的托管行列表数据，用户展示
   * @type {Array}
   */
  public bankListFilteredData: Array<FundConfigBankModel> = [];

  /**
   * 当前活跃的托管行ID
   * @type {string}
   */
  public activedBankId = "";

  /**
   * 当前活跃的托管行名称
   * @type {string}
   */
  public activedBankName = "";

  /**
   * 当前活跃的托管行是否发送成交单全局配置
   * @type {string}
   */
  public activedBankToSendTradeOrder = "";

  /**
   * 当前活跃的托管行划款方式全局配置
   * @type {string}
   */
  public activedBankPaymentMethod = "";

  /**
   * 当前活跃的托管行备注全局配置
   * @type {string}
   */
  public activedBankNote = "";

  /**
   * 基金配置列表数据
   * @type {Array}
   */
  public fundListData: Array<FundConfigModel> = [];

  /**
   * 用户搜索的基金名称
   */
  public userSearchFundName = "";

  /**
   * 当前分页信息
   */
  public pageInfo: PaginationModel = {
    currentPageNum: 1,
    pageSize: 10,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };

  /**
   * 基金配置模态框绑定的数据对象
   */
  public modalData: FundConfigModalDataModel = {
    fundCode: "",
    fundName: "",
    toSendTradeOrder: "",
    paymentMethod: "",
    note: ""
  };

  @ViewChild('fundConfigModal')
  public fundConfigModal: ElementRef;

  constructor(public service: InterbankService, public router: Router) {
  }

  ngOnInit() {
    this.bankSearch().add(() => {
      this.autoGetFundsConfigListDataByFirstBankId();
    });
  }

  /**
   * 托管行列表数据本地过滤搜索，不发起HTTP请求
   * @param bankName
   * @returns {Array<FundConfigBankModel>}
   */
  public bankLocalSearch(bankName: string = ""): Array<FundConfigBankModel> {
    console.log(`--------------托管行列表数据本地过滤搜索，用户输入了： ${bankName}-------------------------`);
    let result: Array<FundConfigBankModel> = this.bankListData;
    bankName = bankName.trim();
    if (bankName !== "") {
      result = this.bankListData.filter(item => item.shortName.indexOf(bankName) !== -1);
    }
    this.bankListFilteredData = result;
    return result;
  }

  /**
   * 获取托管行列表数据,发起HTTP请求
   * @returns {Subscription}
   */
  public bankSearch(): Subscription {
    return this.service.getConfigBankListData().subscribe((data) => {
      this.bankListData = (data != null) ? data : [];
      this.bankListFilteredData = (data != null) ? data : [];
    });
  }

  /**
   * 根据托管行ID和分页信息查询相关基金配置列表数据
   * @param {string} bankId
   * @param {string} bankName
   * @param {string} fundName
   * @param {string} toSendTradeOrder
   * @param {string} paymentMethod
   * @param {string} note
   * @returns {Subscription}
   */
  public getFundsConfigListDataByBankId(bankId: string = this.activedBankId,
                                        bankName: string = this.activedBankName,
                                        fundName: string = this.userSearchFundName,
                                        toSendTradeOrder: string = this.activedBankToSendTradeOrder,
                                        paymentMethod: string = this.activedBankPaymentMethod,
                                        note: string = this.activedBankNote): Subscription {
    this.activedBankId = bankId;
    this.activedBankName = bankName;
    this.activedBankToSendTradeOrder = toSendTradeOrder;
    this.activedBankPaymentMethod = paymentMethod;
    this.activedBankNote = note;
    return this.service.getFundsConfigListDataByBankId(bankId,
      this.pageInfo.currentPageNum <= 0 ? 1 : this.pageInfo.currentPageNum,
      this.pageInfo.pageSize,
      fundName)
      .subscribe((data) => {
        if (data != null && data.list != null) {
          this.fundListData = data.list;
          this.pageInfo.currentPageNum = data.pageNum > 0 ? data.pageNum : 1;
          this.pageInfo.pageSize = data.pageSize > 0 ? data.pageSize : 1;
          this.pageInfo.totalPages = data.pages > 0 ? data.pages : 1;
          this.pageInfo.total = data.total;
          this.pageInfo.startRow = data.startRow;
          this.pageInfo.endRow = data.endRow;
          this.fundListData.forEach((item, index) => {
            item.__FE_SORT_ID__ = this.createIndexByOffset(index + 1);
          });
        }
      });
  }

  /**
   * 根据托管行列表的第一条数据信息查询相关基金配置列表数据
   */
  public autoGetFundsConfigListDataByFirstBankId() {
    if (this.bankListFilteredData.length > 0) {
      const initData: FundConfigBankModel = _.first(this.bankListFilteredData);
      if (initData != null) {
        this.getFundsConfigListDataByBankId(
          initData.bankId,
          initData.shortName,
          this.userSearchFundName,
          initData.toSendTradeOrder,
          initData.paymentMethod,
          initData.note
      )
        ;
      }
    }
  }

  /**
   * 根据页码请求查询相关基金配置列表数据,如果当前活动页码就是目标页码，则不进行任何查询
   * 直接返回
   * @param currentPageNum
   */
  public pageNavigation(currentPageNum: number) {
    this.pageInfo.currentPageNum = currentPageNum <= 0 ? 1 : currentPageNum;
    this.getFundsConfigListDataByBankId(
      this.activedBankId,
      this.activedBankName,
      this.userSearchFundName,
      this.activedBankToSendTradeOrder,
      this.activedBankPaymentMethod,
      this.activedBankNote);
  }

  /**
   * 改变每页显示记录数
   * @param pageSize
   */
  public pageSizeChange(pageSize: number) {
    if (pageSize !== this.pageInfo.pageSize) {
      this.pageInfo.pageSize = pageSize;
      this.pageInfo.currentPageNum = 1;
      this.getFundsConfigListDataByBankId(
        this.activedBankId,
        this.activedBankName,
        this.userSearchFundName,
        this.activedBankToSendTradeOrder,
        this.activedBankPaymentMethod,
        this.activedBankNote);
    }
  }

  /**
   * 基于现托管行，根据用户输入，发起基金搜索
   * @returns {Subscription}
   */
  public fundSearch(): Subscription {
    return this.getFundsConfigListDataByBankId();
  }

  /**
   * 重置基金搜索条件
   */
  public resetFundSearch() {
    Util.resetInputs('ibt-search-input');
    this.userSearchFundName = "";
  }

  /**
   * 切换到基金配置详情界面
   */
  public switch2Detail() {
    this.configViewStatus = {
      global: false,
      detail: true
    };
  }

  /**
   * 切换到托管行统一配置界面
   */
  public switch2Global() {
    this.configViewStatus = {
      global: true,
      detail: false
    };
  }

  /**
   * 根据偏移量及当前分页信息，算出一个序号
   * @param offset
   * @returns {number}
   */
  public createIndexByOffset(offset: number): number {
    const result = (this.pageInfo.currentPageNum - 1) * this.pageInfo.pageSize + offset;
    return result;
  }

  /**
   * 打开基金配置模态框并设置其数据
   * @param fundName
   * @param fundCode
   * @param toSendTradeOrder
   * @param paymentMethod
   * @param note
   */
  public toggleFundConfigModalOpen(fundName: string, fundCode: string, toSendTradeOrder: string, paymentMethod: string, note: string) {
    this.setModalData({fundName, fundCode, toSendTradeOrder, paymentMethod, note});
    return Util.$(this.fundConfigModal.nativeElement).modal('show');
  }

  /**
   * 关闭基金配置模态框并重新设置其数据
   */
  public toggleFundConfigModalClose() {
    this.setModalData();
    return Util.$(this.fundConfigModal.nativeElement).modal('hide');
  }

  /**
   * 设置基金配置模态框映射对象
   * @param fundName
   * @param fundCode
   * @param toSendTradeOrder
   * @param paymentMethod
   * @param note
   * @returns {{fundName, fundCode, toSendTradeOrder, paymentMethod, note}}
   */
  public setModalData({fundName = "", fundCode = "", toSendTradeOrder = "", paymentMethod = "", note = ""} = {}): FundConfigModalDataModel {
    return this.modalData = {
      fundName,
      fundCode,
      toSendTradeOrder,
      paymentMethod,
      note
    };
  }

  /**
   * 更新指定托管行的全局配置
   * @param bankId
   * @param toSendTradeOrder
   * @param paymentMethod
   * @returns {Observable<any>}
   */
  public updateBankGlobalConfig(bankId: string = this.activedBankId,
                                toSendTradeOrder: string = this.activedBankToSendTradeOrder,
                                paymentMethod: string = this.activedBankPaymentMethod,
                                note: string = this.activedBankNote): Subscription {
    return this.service.updateBankGlobalConfig(bankId, toSendTradeOrder, paymentMethod, note)
      .subscribe((data) => {
        if (data && data === 'success') {
          this.pageInfo.currentPageNum = 1;
          this.bankSearch();
          this.getFundsConfigListDataByBankId();
          window['swal']('提示', '保存成功！', 'success');
        } else {
          window['swal']('提示', '保存失败！', 'error');
        }
      });
  }

  /**
   * 更新指定基金的支付参数配置
   * @param fundCode
   * @param toSendTradeOrder
   * @param paymentMethod
   * @param note
   * @returns {Observable<any>}
   */
  public updateFundConfig({
                            fundCode = this.modalData.fundCode,
                            toSendTradeOrder = this.modalData.toSendTradeOrder,
                            paymentMethod = this.modalData.paymentMethod,
                            note = this.modalData.note
                          } = {}): Subscription {
    return this.service.updateFundConfig(this.activedBankId, fundCode, toSendTradeOrder, paymentMethod, note)
      .subscribe((data) => {
        this.toggleFundConfigModalClose();
        if (data && data === 'success') {
          this.getFundsConfigListDataByBankId();
          window['swal']('提示', '保存成功！', 'success');
        } else {
          window['swal']('提示', '保存失败！', 'error');
        }
      });
  }

  /**
   * 重置／删除指定基金支付参数配置询问提示
   */
  public deleteFundConfigConfirm(bankId: string, fundCode: string, fundName: string) {
    window['swal']({
      title: '提示',
      text: `确认重置基金名称为<span class="text-red">${fundName}</span>的支付参数配置吗？`,
      type: 'info',
      html: true,
      showCancelButton: true,
      closeOnConfirm: false,
      disableButtonsOnConfirm: true,
      showLoaderOnConfirm: true,
      confirmLoadingButtonColor: '#DD6B55',
      cancelButtonText: "否",
      confirmButtonText: "是"
    }, () => {
      this.deleteFundConfig(bankId, fundCode).subscribe((data) => {
        if (data && data === 'success') {
          this.getFundsConfigListDataByBankId();
          window['swal']('提示', `重置基金名称为${fundName}的支付参数配置成功！`, 'success');
        } else {
          window['swal']('提示', `重置基金名称为${fundName}的支付参数配置失败！`, 'error');
        }
      });
    });
  }

  /**
   * 重置／删除指定基金支付参数配置
   * @param bankId 托管行ID
   * @param fundCodeList 基金代码列表字符串，逗号分隔
   * @returns {Observable<any>}
   */
  public deleteFundConfig(bankId: string, fundCodeList: string): Observable<any> {
    return this.service.deleteFundConfig(bankId, fundCodeList);
  }
}
